import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    currentUser: {},
    data: null,
    merchant: null,
    TotalAccountBalance: 0,
  },

  mutations: {
    editMerchant(state, merchant) {
      state.merchant = merchant;
    },
    login(state, user) {
      state.currentUser = user;
      window.sessionStorage.setItem("user", JSON.stringify(user));
    },
    setData(state, data) {
      if (!state.data) {
        state.data = JSON.parse(window.sessionStorage.getItem("data"));
      }
      state.data = { ...state.data, ...data };
      window.sessionStorage.setItem("data", JSON.stringify(state.data));
    },
    TotalAccountBalance(state, data) {
      let num = Number(data);
      if (typeof num === "number") {
        state.TotalAccountBalance = num;
        window.sessionStorage.setItem("TotalAccountBalance", data);
      } else {
        throw num;
      }
    },
    rights(state, rights) {
      state.rights = rights;
      window.sessionStorage.setItem("rights", JSON.stringify(rights));
    },
  },
  getters: {
    user: (state) => {
      if (state.currentUser.name) {
        return state.currentUser;
      } else {
        return JSON.parse(window.sessionStorage.getItem("user"));
      }
    },
    data: (state) => {
      if (state.data) {
        return state.data;
      } else {
        return JSON.parse(window.sessionStorage.getItem("data"));
      }
    },
    TotalAccountBalance: (state) => {
      if (state.TotalAccountBalance) {
        return state.TotalAccountBalance;
      } else {
        return JSON.parse(window.sessionStorage.getItem("TotalAccountBalance"));
      }
    },
    rights: (state) => {
      if (state.rights) {
        return state.rights;
      } else {
        return JSON.parse(window.sessionStorage.getItem("rights"));
      }
    },
  },
  actions: {
    test() {
      console.log(123);
    },
  },
  modules: {},
});
